var MOCHAT = {}
var ENVENS = {
  dataType: {}
}

var jsAPIList = [
  '$refresh',
  '$Toast',
  '$sendMessage'
]

function _INIT () {
  function jsAPIINIT (apiAction) {
    MOCHAT[apiAction] = function(...arg) {
      window.parent.postMessage(
        {
          apiAction,
          params: arg
        },
        '*'
      )
    }
  }

  jsAPIList.forEach(item => {
    jsAPIINIT(item)
  })

  MOCHAT.getExtData = function(callback) {
    var id = Date.now().toString(36) + parseInt(Math.random() * 100000 + '').toString(36)
    ENVENS.dataType[id] = callback
    window.parent.postMessage(
      {
        apiAction: 'getExtData',
        params: id
      },
      '*'
    )
  }

  window.MOCHAT = MOCHAT
}
_INIT()
window.addEventListener('message', (e) => {
  var eventData = e.data
  if (eventData.apiAction === 'accData') {
    if (ENVENS.dataType[eventData.id]) {
      ENVENS.dataType[eventData.id](eventData.params)
    }
  }
})

